package com.coding365.service.code.service.impl;

import com.coding365.service.code.dao.LagouAuthCodeMapper;
import com.coding365.service.code.entity.LagouAuthCode;
import com.coding365.service.code.service.CodeService;
import com.coding365.service.code.service.rpc.EmailFeignClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private LagouAuthCodeMapper lagouAuthCodeMapper;

    @Autowired
    private EmailFeignClient emailFeignClient;

    @Override
    public Boolean create(String email) {
        //生成6位随机验证码
        String code = UUID.randomUUID().toString().toLowerCase().substring(0, 6);
        //调用email服务发送验证码到注册用户的邮箱
        Boolean result = emailFeignClient.postCode(email,code);
        //发送成功，将验证码存到数据库中
        if (result){
            Date now = new Date();
            Date expireTime = new Date(now.getTime() + 10 * 60 * 1000);
            LagouAuthCode lagouAuthCode = new LagouAuthCode();
            lagouAuthCode.setCode(code);
            lagouAuthCode.setCreateTime(now);
            lagouAuthCode.setExpireTime(expireTime);
            lagouAuthCode.setEmail(email);
            lagouAuthCodeMapper.insertAuthCode(lagouAuthCode);
            return true;
        }
        return false;
    }

    @Override
    public Integer validate(String email, String code) {
        //查询时间最近的验证码
        LagouAuthCode lagouAuthCode = lagouAuthCodeMapper.selectLastAuthCodeWithEmail(email);
        if (lagouAuthCode == null
                || StringUtils.isEmpty(lagouAuthCode.getCode())
                ||!lagouAuthCode.getCode().equals(code)){
            return 1;
        }
        //判断是否过期
        Date now = new Date();
        if (lagouAuthCode.getExpireTime().before(now)){
            System.out.println("验证码过期！！");
            return 1;
        }
        return 0;
    }
}
